<template>
  <div class="photo-manager">
    <div class="photo-header">
      <h4>{{ member.name }} 的照片</h4>
      <button @click="showUploadForm = true" class="btn primary">
        <span>📷</span> 上传照片
      </button>
    </div>
    
    <!-- 照片网格 -->
    <div class="photo-grid" v-if="member.photos && member.photos.length > 0">
      <div 
        v-for="(photo, index) in member.photos" 
        :key="index"
        class="photo-item"
        @click="selectPhoto(photo, index)"
      >
        <img :src="photo.url" :alt="photo.description || '家族照片'" class="photo-thumbnail">
        <div class="photo-overlay">
          <div class="photo-actions">
            <button @click.stop="editPhoto(photo, index)" class="action-btn edit">✏️</button>
            <button @click.stop="deletePhoto(index)" class="action-btn delete">🗑️</button>
          </div>
        </div>
        <div class="photo-info">
          <p class="photo-date">{{ formatDate(photo.uploadDate) }}</p>
          <p v-if="photo.description" class="photo-description">{{ photo.description }}</p>
        </div>
      </div>
    </div>
    
    <!-- 空状态 -->
    <div v-else class="photo-empty">
      <div class="empty-icon">📷</div>
      <p>还没有照片</p>
      <button @click="showUploadForm = true" class="btn primary">
        上传第一张照片
      </button>
    </div>
    
    <!-- 上传照片表单 -->
    <div v-if="showUploadForm" class="modal-overlay" @click="closeUploadForm">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h4>上传照片</h4>
          <button @click="closeUploadForm" class="close-btn">&times;</button>
        </div>
        <div class="modal-body">
          <div class="upload-area" @click="triggerFileInput" @drop="handleDrop" @dragover.prevent>
            <input 
              ref="fileInput" 
              type="file" 
              accept="image/*" 
              multiple 
              @change="handleFileSelect"
              style="display: none"
            >
            <div class="upload-icon">📁</div>
            <p>点击选择文件或拖拽照片到此处</p>
            <p class="upload-hint">支持 JPG, PNG, GIF 格式</p>
          </div>
          
          <!-- 预览区域 -->
          <div v-if="selectedFiles.length > 0" class="preview-area">
            <h5>预览 ({{ selectedFiles.length }} 张照片)</h5>
            <div class="preview-grid">
              <div 
                v-for="(file, index) in selectedFiles" 
                :key="index"
                class="preview-item"
              >
                <img :src="file.preview" :alt="file.name" class="preview-image">
                <div class="preview-info">
                  <input 
                    v-model="file.description" 
                    placeholder="照片描述" 
                    class="description-input"
                  >
                  <button @click="removeFile(index)" class="remove-btn">×</button>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button @click="closeUploadForm" class="btn secondary">取消</button>
          <button @click="uploadPhotos" class="btn primary" :disabled="selectedFiles.length === 0 || isUploading">
            {{ isUploading ? '上传中...' : '上传照片' }}
          </button>
        </div>
      </div>
    </div>
    
    <!-- 照片详情弹窗 -->
    <div v-if="selectedPhoto" class="modal-overlay" @click="closePhotoDetail">
      <div class="modal-content photo-detail" @click.stop>
        <div class="modal-header">
          <h4>照片详情</h4>
          <button @click="closePhotoDetail" class="close-btn">&times;</button>
        </div>
        <div class="modal-body">
          <img :src="selectedPhoto.url" :alt="selectedPhoto.description" class="detail-image">
          <div class="detail-info">
            <p><strong>上传时间：</strong>{{ formatDate(selectedPhoto.uploadDate) }}</p>
            <p v-if="selectedPhoto.description"><strong>描述：</strong>{{ selectedPhoto.description }}</p>
          </div>
        </div>
        <div class="modal-footer">
          <button @click="closePhotoDetail" class="btn secondary">关闭</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed } from 'vue';
import { personService } from '@/services/person.service.js';

export default {
  name: 'PhotoManager',
  props: {
    member: {
      type: Object,
      required: true
    }
  },
  emits: ['update-photos'],
  setup(props, { emit }) {
    const showUploadForm = ref(false);
    const selectedFiles = ref([]);
    const selectedPhoto = ref(null);
    const fileInput = ref(null);
    const isUploading = ref(false);
    
    const triggerFileInput = () => {
      fileInput.value.click();
    };
    
    const handleFileSelect = (event) => {
      const files = Array.from(event.target.files);
      addFiles(files);
    };
    
    const handleDrop = (event) => {
      event.preventDefault();
      const files = Array.from(event.dataTransfer.files).filter(file => file.type.startsWith('image/'));
      addFiles(files);
    };
    
    const addFiles = (files) => {
      files.forEach(file => {
        const reader = new FileReader();
        reader.onload = (e) => {
          selectedFiles.value.push({
            file,
            name: file.name,
            preview: e.target.result,
            description: ''
          });
        };
        reader.readAsDataURL(file);
      });
    };
    
    const removeFile = (index) => {
      selectedFiles.value.splice(index, 1);
    };
    
    const uploadPhotos = async () => {
      if (selectedFiles.value.length === 0) return;
      
      isUploading.value = true;
      try {
        // 创建新的照片对象
        const newPhotos = selectedFiles.value.map(file => ({
          url: file.preview,
          description: file.description,
          uploadDate: new Date().toISOString(),
          fileName: file.name
        }));
        
        // 合并现有照片和新照片
        const updatedPhotos = [...(props.member.photos || []), ...newPhotos];
        
        // 调用API保存照片
        await personService.updatePersonPhotos(props.member.id, updatedPhotos);
        
        // 通知父组件更新
        emit('update-photos', updatedPhotos);
        
        closeUploadForm();
      } catch (error) {
        console.error('上传照片失败:', error);
        alert('上传照片失败，请重试');
      } finally {
        isUploading.value = false;
      }
    };
    
    const selectPhoto = (photo, index) => {
      selectedPhoto.value = { ...photo, index };
    };
    
    const editPhoto = (photo, index) => {
      // 编辑照片功能
      console.log('编辑照片:', photo, index);
    };
    
    const deletePhoto = async (index) => {
      if (confirm('确定要删除这张照片吗？')) {
        try {
          const updatedPhotos = [...(props.member.photos || [])];
          updatedPhotos.splice(index, 1);
          
          // 调用API保存更新
          await personService.updatePersonPhotos(props.member.id, updatedPhotos);
          
          // 通知父组件更新
          emit('update-photos', updatedPhotos);
        } catch (error) {
          console.error('删除照片失败:', error);
          alert('删除照片失败，请重试');
        }
      }
    };
    
    const closeUploadForm = () => {
      showUploadForm.value = false;
      selectedFiles.value = [];
      if (fileInput.value) {
        fileInput.value.value = '';
      }
    };
    
    const closePhotoDetail = () => {
      selectedPhoto.value = null;
    };
    
    const formatDate = (dateString) => {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleDateString('zh-CN');
    };
    
    return {
      showUploadForm,
      selectedFiles,
      selectedPhoto,
      fileInput,
      isUploading,
      triggerFileInput,
      handleFileSelect,
      handleDrop,
      removeFile,
      uploadPhotos,
      selectPhoto,
      editPhoto,
      deletePhoto,
      closeUploadForm,
      closePhotoDetail,
      formatDate
    };
  }
};
</script>

<style scoped>
.photo-manager {
  padding: 20px;
}

.photo-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.photo-header h4 {
  margin: 0;
  color: #333;
}

.photo-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.photo-item {
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  cursor: pointer;
  transition: transform 0.2s ease;
}

.photo-item:hover {
  transform: translateY(-2px);
}

.photo-thumbnail {
  width: 100%;
  height: 150px;
  object-fit: cover;
}

.photo-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  opacity: 0;
  transition: opacity 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.photo-item:hover .photo-overlay {
  opacity: 1;
}

.photo-actions {
  display: flex;
  gap: 10px;
}

.action-btn {
  width: 32px;
  height: 32px;
  border: none;
  border-radius: 50%;
  background: white;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  transition: background-color 0.2s ease;
}

.action-btn.edit:hover {
  background: #007bff;
  color: white;
}

.action-btn.delete:hover {
  background: #dc3545;
  color: white;
}

.photo-info {
  padding: 10px;
  background: white;
}

.photo-date {
  font-size: 12px;
  color: #666;
  margin: 0 0 5px 0;
}

.photo-description {
  font-size: 12px;
  color: #333;
  margin: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.photo-empty {
  text-align: center;
  padding: 40px 20px;
  color: #666;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 10px;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  max-width: 600px;
  width: 90%;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.modal-header h4 {
  margin: 0;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #666;
}

.modal-body {
  padding: 20px;
}

.upload-area {
  border: 2px dashed #ddd;
  border-radius: 8px;
  padding: 40px;
  text-align: center;
  cursor: pointer;
  transition: border-color 0.2s ease;
}

.upload-area:hover {
  border-color: #007bff;
}

.upload-icon {
  font-size: 48px;
  margin-bottom: 10px;
}

.upload-hint {
  font-size: 12px;
  color: #666;
  margin-top: 5px;
}

.preview-area {
  margin-top: 20px;
}

.preview-area h5 {
  margin: 0 0 15px 0;
}

.preview-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 15px;
}

.preview-item {
  border: 1px solid #ddd;
  border-radius: 8px;
  overflow: hidden;
}

.preview-image {
  width: 100%;
  height: 100px;
  object-fit: cover;
}

.preview-info {
  padding: 10px;
  display: flex;
  gap: 5px;
}

.description-input {
  flex: 1;
  padding: 5px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 12px;
}

.remove-btn {
  width: 24px;
  height: 24px;
  border: none;
  border-radius: 50%;
  background: #dc3545;
  color: white;
  cursor: pointer;
  font-size: 14px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 20px;
  border-top: 1px solid #eee;
}

.photo-detail .modal-content {
  max-width: 800px;
}

.detail-image {
  width: 100%;
  max-height: 400px;
  object-fit: contain;
  margin-bottom: 15px;
}

.detail-info p {
  margin: 5px 0;
}

.btn {
  padding: 8px 16px;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s ease;
}

.btn.primary {
  background: #007bff;
  color: white;
  border-color: #007bff;
}

.btn.primary:hover {
  background: #0056b3;
  border-color: #0056b3;
}

.btn.secondary {
  background: #6c757d;
  color: white;
  border-color: #6c757d;
}

.btn.secondary:hover {
  background: #545b62;
  border-color: #545b62;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
</style> 